import 'package:environmental_les_app/common/style/colours.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';
import 'package:syncfusion_flutter_gauges/gauges.dart';

// AQI 卡片主组件
class AqiCard extends StatelessWidget {
  // 首要污染物
  final String? primaryPollutant;
  //是否显示查看更多
  final bool showMore;
  //aqi 最大值
  final double maxAqi;

  /// api 值
  final double aqiValue;

  /// 污染物数值
  final Map<String, double>? pollutantValue;

  const AqiCard(
      {super.key,
      this.primaryPollutant,
      this.showMore = false,
      this.maxAqi = 500,
      this.aqiValue = 0,
      this.pollutantValue});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 214,
      padding: const EdgeInsets.only(left: 15, right: 15, top: 10),
      margin: const EdgeInsets.only(left: 15, right: 15, top: 10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          image: DecorationImage(
            image: AssetImage(
                ImageUtils.getImgPath(_getAqiLevelDecoration(aqiValue))),
            fit: BoxFit.cover,
          )),
      child: Column(
        mainAxisSize: MainAxisSize.min, // 让 Column 包裹内容
        children: [
          // 顶部：首要污染物和查看更多
          _buildHeader(),
          vGap10,
          // 中部：仪表盘和污染物列表
          SizedBox(
            height: 150, // 固定高度以适应内容
            child: Row(
              children: [
                // 左侧仪表盘
                Expanded(
                  flex: 5,
                  child: _buildRadialGauge(),
                ),
                hGap10,
                // 右侧污染物列表
                Expanded(
                  flex: 5,
                  child: _buildPollutantList(),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 构建顶部区域
  Widget _buildHeader() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Container(
          color: Colors.white,
          width: 3,
          height: 14,
        ),
        hGap10,
        Text(
          '首要污染物: ${primaryPollutant ?? "未知"}',
          style: const TextStyle(color: Colors.white, fontSize: 15),
        ),
        const Spacer(),
        Visibility(
          visible: showMore,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.6),
              border: Border.all(color: Colours.textWhite, width: 1),
              borderRadius: BorderRadius.circular(40),
            ),
            child: const Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '查看更多',
                  style: TextStyle(
                      color: Colours.appMain,
                      fontWeight: FontWeight.w500,
                      fontSize: 14),
                ),
                SizedBox(width: 4),
                Icon(
                  Icons.play_arrow,
                  size: 16,
                  color: Colours.color1F59EF,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  // 构建 Syncfusion 径向仪表盘
  Widget _buildRadialGauge() {
    return SfRadialGauge(
      axes: <RadialAxis>[
        RadialAxis(
          minimum: 0,
          maximum: maxAqi, // AQI 最大值通常设为 300 或 500
          showLabels: false,
          showTicks: false,
          startAngle: 150,
          endAngle: 30,
          axisLineStyle: AxisLineStyle(
            thickness: 0.15,
            thicknessUnit: GaugeSizeUnit.factor,
            color: Colors.white.withOpacity(0.3),
          ),
          pointers: <GaugePointer>[
            RangePointer(
              value: aqiValue,
              width: 0.15,
              sizeUnit: GaugeSizeUnit.factor,
              cornerStyle: CornerStyle.bothCurve,
              gradient: SweepGradient(
                colors: _getAqiColor(aqiValue),
                stops: const <double>[0.25, 0.75],
              ),
            ),
          ],
          annotations: <GaugeAnnotation>[
            GaugeAnnotation(
              widget: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  vGap20,
                  const Text(
                    'AQI 指数',
                    style: TextStyle(
                      color: Colours.bgColor,
                      fontSize: 14,
                    ),
                  ),
                  Text(
                    aqiValue.toStringAsFixed(0),
                    style: const TextStyle(
                      color: Colours.textF7FBFF,
                      fontSize: 36,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  aqiValue <= 100
                      ? Container(
                          height: 28,
                          width: 28,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color:
                                _getPollutantColor(aqiValue.toString()), // 绿色
                            shape: BoxShape.circle,
                          ),
                          child: Text(
                            _getAqiLevelText(
                                aqiValue), // 设计稿显示“优”，尽管126通常是“轻度污染”
                            style: const TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.bold),
                          ),
                        )
                      : Container(
                          height: 28,
                          width: 44,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            color:
                                _getPollutantColor(aqiValue.toString()), // 绿色
                          ),
                          child: Text(
                            _getAqiLevelText(
                                aqiValue), // 设计稿显示“优”，尽管126通常是“轻度污染”
                            style: const TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                ],
              ),
              angle: 90,
              positionFactor: 0.1,
            )
          ],
        )
      ],
    );
  }

  // api 仪表配色
  List<Color> _getAqiColor(double aqi) {
    if (aqi <= 100) {
      return <Color>[
        const Color(0xFFFFF000),
        const Color(0xFFFF7E00),
      ]; // 优
    } else if (aqi <= 200) {
      return <Color>[
        const Color(0xFFFFF000),
        const Color(0xFFFF7E00),
      ];
    } else {
      return <Color>[
        const Color(0xFF99004C),
        const Color(0xFF7E0023),
      ];
    }
  }

  //aqi 颜色等级优良等级卡片背景图
  String _getAqiLevelDecoration(double aqi) {
    if (aqi <= 100) {
      return 'bg_home_aqi_1'; // 优
    } else if (aqi <= 200) {
      return 'bg_home_aqi_2';
    } else {
      return 'bg_home_aqi_3';
    }
  }

  // aqi 颜色等级优良等级文字
  String _getAqiLevelText(double aqi) {
    if (aqi <= 50) {
      return '优';
    } else if (aqi <= 100) {
      return '良';
    } else if (aqi <= 150) {
      return '轻度';
    } else if (aqi <= 200) {
      return '中度';
    } else if (aqi <= 300) {
      return '重度';
    } else {
      return '严重';
    }
  }

  // 污染物优良等级配色
  Color _getPollutantColor(String value) {
    double val = double.tryParse(value) ?? 0;
    if (val <= 50) {
      return const Color(0xFF00E400); // 优
    } else if (val <= 100) {
      return const Color(0xFFFFF000); // 良
    } else if (val <= 150) {
      return const Color(0xFFFF7E00); // 轻度污染
    } else if (val <= 200) {
      return const Color(0xFFFF0000); // 中度污染
    } else if (val <= 300) {
      return const Color(0xFF99004C); // 重度污染
    } else {
      return const Color(0xFF7E0023); // 严重污染
    }
  }

  // 构建右侧污染物列表
  Widget _buildPollutantList() {
    var pm25 = pollutantValue?['pm25']?.toStringAsFixed(1) ?? '--';
    var pm10 = pollutantValue?['pm10']?.toStringAsFixed(1) ?? '--';
    var so2 = pollutantValue?['so2']?.toStringAsFixed(1) ?? '--';
    var no2 = pollutantValue?['no2']?.toStringAsFixed(1) ?? '--';
    var co = pollutantValue?['co']?.toStringAsFixed(1) ?? '--';
    var o3 = pollutantValue?['o3']?.toStringAsFixed(1) ?? '--';

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _PollutantRow(
            name: 'PM₂.₅',
            value: pm25,
            unit: 'µg/m³',
            color: _getPollutantColor(pm25)),
        _PollutantRow(
            name: 'PM₁₀',
            value: pm10,
            unit: 'µg/m³',
            color: _getPollutantColor(pm10)),
        _PollutantRow(
            name: 'SO₂',
            value: so2,
            unit: 'µg/m³',
            color: _getPollutantColor(so2)),
        _PollutantRow(
            name: 'NO₂',
            value: no2,
            unit: 'µg/m³',
            color: _getPollutantColor(no2)),
        _PollutantRow(
            name: 'CO',
            value: co,
            unit: 'mg/m³',
            color: _getPollutantColor(co)),
        _PollutantRow(
            name: 'O₃',
            value: o3,
            unit: 'µg/m³',
            color: _getPollutantColor(o3)),
      ],
    );
  }
}

// 单个污染物行的组件，用于代码复用
class _PollutantRow extends StatelessWidget {
  final String name;
  final String value;
  final String unit;
  final Color color;

  const _PollutantRow({
    required this.name,
    required this.value,
    required this.unit,
    required this.color,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2.0),
      child: Row(
        children: [
          Container(
            width: 8,
            height: 8,
            decoration: BoxDecoration(
              color: color,
              shape: BoxShape.circle,
            ),
          ),
          hGap4,
          SizedBox(
            width: 55, // 固定宽度以对齐数值
            child: Text(name,
                style: const TextStyle(color: Colours.bgColor, fontSize: 14)),
          ),
          const Spacer(),
          Text(value,
              style: const TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.bold)),
          const SizedBox(width: 4),
          Text(unit,
              style: const TextStyle(color: Colours.textC6D1DB, fontSize: 12)),
        ],
      ),
    );
  }
}
